package com.ltedu.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedisTool
 * @Auther: Jerry
 * @Date: 2020/11/3 19:13
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Service
public class RedisTool {

    private Logger logger = LoggerFactory.getLogger(RedisTool.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 批量删除对应的value
     *
     * @param keys key数组
     */
    public void delBatchKey(final String... keys) {
        for (String key : keys) {
            delByKey(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern string
     */
    public void delPattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除key
     *
     * @param key string
     */
    public void delByKey(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key key
     * @return boolean false or true
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key string
     * @return object
     */
    public Object get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存,长久有效
     *
     * @param key   string
     * @param value object
     * @return boolean false or true
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (DataAccessException e) {
            logger.error("Write RedisCache failure:" + e);
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key        string
     * @param value      object
     * @param expireTime 过期时间
     * @return boolean false or true
     */
    public boolean setWithTime(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (DataAccessException e) {
            logger.error("Write RedisCache failure:" + e);
        }
        return result;
    }

    /**
     * 向hash表写入数据
     *
     * @param key   键名，即hash表名
     * @param field 字段名
     * @param value 值
     */
    public void hset(String key, String field, String value) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field) || StringUtils.isEmpty(value)) {
            logger.debug("Read RedisCache failure: Parameter cannot Empty");
        }
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 为哈希表 key 中的域 field 的值加上增量 increment
     *
     * @param key   键名，即hash表名
     * @param field 字段名
     * @param value 值
     */
    public long increment(String key, String field, long value) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field) || StringUtils.isEmpty(value)) {
            logger.debug("Read RedisCache failure: Parameter cannot Empty");
        }
        return redisTemplate.opsForHash().increment(key, field, value);
    }

    /**
     * 获取为哈希表 key 中的域
     *
     * @param key   键名，即hash表名
     * @param field 字段名
     */
    public Object hget(String key, String field) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
            logger.debug("Read RedisCache failure: Parameter cannot Empty");
        }
        return redisTemplate.opsForHash().get(key, field);
    }

    /**
     * 删除为哈希表 key
     *
     * @param key   键名，即hash表名
     * @param field 字段名
     */
    public Object deleteHash(String key, String field) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
            logger.debug("Read RedisCache failure: Parameter cannot Empty");
        }
        return redisTemplate.opsForHash().delete(key, field);
    }

    /**
     * 判断hash中是否有相应字段
     *
     * @param key   键名，即hash表名
     * @param field 字段名
     * @return 存在返回true, 否则返回false
     */
    public boolean existKeyValue(String key, String field) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(field)) {
            return false;
        } else {
            HashOperations<String, String, Object> operations = redisTemplate.opsForHash();
            //redis中存储的sessionId前缀spring:session:sessions:
            return operations.hasKey("spring:session:sessions:" + key, field);
        }
    }

    public void set(Object key, Long timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 为哈希表 key 中的域 field 的值加上增量 increment
     *
     * @param key   键名，即hash表名
     * @param value 值
     */
    public long increment(String key, long value) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
            logger.debug("Read RedisCache failure: Parameter cannot Empty");
        }

        return redisTemplate.opsForValue().increment(key, value);
    }

    /**
     * 向redis里面存key 假如key存在就返回false 假如key不存在就把key存进去返回true
     * @param key
     * @param value
     * @return
     */
    public boolean setIfAbsent (String key,String value){
        return redisTemplate.opsForValue().setIfAbsent(key,value);
    }

    /**
     * 设置key超时时间
     * @param key
     * @param timeout
     * @return
     */
    public boolean expire(String key,long timeout){
        return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }


    /**
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setLock(final String key, Object value,int time) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result= operations.setIfAbsent(key, value);
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
            return  result;
        } catch (Exception e) {
            logger.error("scheduler error:"+e.getMessage());
        }
        return result;
    }
}
